package com.xxq.semester.service.impl.utils;

import com.xxq.semester.service.utils.VerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;

@Service
public class VerificationServiceImpl implements VerificationService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void sendVerificationCode(String to, String code) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1311624739@qq.com");
        message.setTo(to);
        message.setSubject("【AI教育资源平台】验证码通知");
        message.setText("您的验证码为 ：" + code + "，有效期为5分钟，请勿泄露。");
        mailSender.send(message);
    }

    @Override
    public String generateAndSaveCode(String email) {
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000)); // 6位数
        redisTemplate.opsForValue().set("email:code:" + email, code, Duration.ofMinutes(5));
        return code;
    }

    @Override
    public boolean verifyCode(String email, String inputCode) {
        String realCode = redisTemplate.opsForValue().get("email:code:" + email);
        return inputCode.equals(realCode);
    }
}
